﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Loader;
using System.Threading.Tasks;

namespace MyFramework.Web.Api
{
    /// <summary>
    /// 插件上下文管理
    /// </summary>
    public class MyPluginsLoadContexts
    {
        #region Fields
        /// <summary>
        /// 插件管理容器
        /// </summary>
        public static ConcurrentDictionary<string, MyAssemblyLoadContext> _myPluginsLoadContexts;

        #endregion

        #region Ctor
        static MyPluginsLoadContexts()
        {
            _myPluginsLoadContexts = new ConcurrentDictionary<string, MyAssemblyLoadContext>();
        }
        #endregion

        #region Methods
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="pluginName"></param>
        /// <param name="context"></param>
        public static void Load(string pluginName, MyAssemblyLoadContext context)
        {
            if (!_myPluginsLoadContexts.ContainsKey(pluginName))
            {
            }
            else
            {
                MyPluginsLoadContexts.Unload(pluginName);
            }
            _myPluginsLoadContexts.GetOrAdd(pluginName, context);
        }
        /// <summary>
        /// 卸载
        /// </summary>
        /// <param name="pluginName"></param>
        public static void Unload(string pluginName)
        {
            MyAssemblyLoadContext assemblyLoadContext = null;
            _myPluginsLoadContexts.TryRemove(pluginName, out assemblyLoadContext);
            if (assemblyLoadContext != null)
                assemblyLoadContext.Unload();
        }
        #endregion
    }
}